<template>
	<view class="w-flex-col page space-y-27">
		<view class="vimg">
			<image src="/static/home/bg.png" mode=""></image>
		</view>
		<view class="w-flex-col section space-y-26">
			<text class="w-self-center text">剩余连接次数</text>
			<view class="w-flex-col w-items-center space-y-22">
				<text class="text_2">{{connect_number}}</text>
				<view class="w-flex-col w-justify-start w-items-center button" @tap="add">
					<text class="font_1 text_3">增加次数</text>
				</view>
			</view>
		</view>
		<view class="w-flex-col section_2 space-y-36">
			<text class="w-self-start font_1 text_4">WIFI列表</text>
			<uv-empty mode="data" icon="/static/my_wifi/nodata.png" marginTop="10%" :show="list.length <=0 "
				iconSize="20"></uv-empty>
			<button class="btn" type="default" plain size="mini" @tap="create" v-show="list.length <=0 ">创建</button>
			<view class="w-flex-col list space-y-38" v-show="list.length">
				<view class="w-flex-row w-justify-between w-items-center" :key="i" v-for="(item, i) in list">
					<view class="w-flex-row space-x-10">
						<image class="image" src="/static/wifi_list/a3845ce230a944077ac7f81671fe4945.png" />
						<view class="w-flex-col w-items-start space-y-8">
							<text class="font_2">{{item.account}}</text>
							<text class="font_1">{{item.store}}</text>
						</view>
					</view>
					<view class="w-flex-col w-justify-start w-items-center text-wrapper" @tap="setConnent(item)"
						v-if="!is_linked || (linked_acount != item.id)">
						<text class="font_3" v-show="!linking && !is_linked">一键连接</text>
						<text class="font_3" v-show="linking && (linked_acount == item.id)">正在连接</text>
						<text class="font_3" v-show="linking && (linked_acount != item.id)">一键连接</text>
						<text class="font_3" v-show="(!linking && is_linked) && (linked_acount != item.id)">一键连接</text>
					</view>
					<view class="w-flex-col w-justify-start w-items-center w-flex-row vcon"
						v-if="(!linking && is_linked) && linked_acount == item.id">
						<view class="vcimg">
							<image src="/static/wifi_list/conn.png" mode=""></image>
						</view>
						<view class="font_con">
							<text class="font_3">已连接</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="ios" v-if="show_tips">
			<view class="close" @tap="show_tips = false">
				<image src="/static/wifi_list/close.png" mode=""></image>
			</view>
			<image class="tip_img" src="/static/wifi_list/tips.jpg" mode=""></image>
		</view>
	</view>
</template>

<script>
	// 加载空组件
	import uEmpty from "@/uni_modules/uv-empty/components/uv-empty/uv-empty.vue";
	const errCodeMap = {
		'12000': 'WIFI未初始化',
		'12001': '系统不支持',
		'12002': '密码错误',
		'12003': '连接超时',
		'12004': '重复连接Wi-Fi',
		'12005': '未打开Wi-Fi开关',
		'12006': '未打开GPS定位开关',
		'12007': '用户拒绝授权链接Wi-Fi',
		'12008': '无效SSID',
		'12009': '系统运营商配置拒绝连接Wi-Fi',
		'12010': '系统错误',
		'12011': '应用在后台无法配置Wi-Fi',
		'12014': '密码错误',
		'1505005': '密码错误',
	}
	export default {
		components: {
			uEmpty
		},
		data() {
			return {
				list: [],
				next: true,
				page: 1,
				connect_number: 0,
				nextAdv: true,
				linking: false,
				is_linked: false,
				wifi: [],
				linked_acount: '',
				wifiList: [],
				show_tips: false,
				videoAd: null
			};
		},
		onLoad() {
			if (wx.createRewardedVideoAd) {
				this.videoAd = wx.createRewardedVideoAd({
					adUnitId: 'adunit-29ed5fd435bd4721'
				})
				this.videoAd.onLoad(() => {})
				this.videoAd.onError((err) => {
					console.error('激励视频光告加载失败', err)
				})
				this.videoAd.onClose(res => {
				    // 用户点击了【关闭广告】按钮
				    if (res && res.isEnded) {
				      // 正常播放结束，可以下发游戏奖励
					  this.setConnectNumber()
				    } else {
				      // 播放中途退出，不下发游戏奖励
						uni.showToast({
							icon:'none',
							title:'请观看完广告'
						})
				    }
					
					this.nextAdv = true;
				})
			}
		},
		onShow() {
			let user = uni.getStorageSync('user')
			if (user) {
				// 更新用户信息
				this.getUser()
				let user = uni.getStorageSync('user')
				this.connect_number = user.connect_number
			}
			this.getWifiList()
		},
		onReachBottom() {
			var that = this
			if (this.next) {
				uni.showLoading({
					title: '正在加载...',
				});
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						// console.log('当前位置的经度：' + res.longitude);
						// console.log('当前位置的纬度：' + res.latitude);
						that.getList(res.longitude, res.latitude)
					}
				});
			}
		},
		onShareAppMessage(res) {
			// console.log(this.shareGood)
			return {
				title: 'WIFI安全一键连',
				path: '/pages/wifi_list/wifi_list',
				imageUrl: ''
			}
		},
		onShareTimeline(res) {
			return {
				title: 'WIFI安全一键连',
				path: '/pages/wifi_list/wifi_list',
				imageUrl: ''
			}
		},
		methods: {
			getList(lng = '', lat = '') {
				this.$http.get('commonWifi', {
					params: {
						page: this.page,
						account: this.wifiList,
						longitude: lng,
						latitude: lat,
					}
				}).then(res => {
					if (res.data.code == 0) {
						this.next = false
						uni.hideLoading()
						return uni.showToast({
							icon: "none",
							title: res.data.msg
						})
					}
					this.list = this.list.concat(res.data.data.data)
					// console.log(res.data.data.data.length)
					// 没有数据并且不是查询
					if (res.data.data.data.length <= 0) {
						this.next = false
					} else {
						this.page += 1
					}
					console.log(this.linking, this.is_linked)
					uni.hideLoading()
				}).catch(err => {

				})
			},
			create() {
				uni.reLaunch({
					url: "/pages/home/home"
				})
			},
			showAd() {
				this.goMy()
				if (this.nextAdv) {
					if (this.videoAd) {
					  this.videoAd.show().catch(() => {
					    // 失败重试
					    this.videoAd.load()
					      .then(() => videoAd.show())
					      .catch(err => {
					        console.error('激励视频 广告显示失败', err)
					      })
					  })
					}
				}
				uni.hideLoading()
			},
			add() {
				// 未登录
				this.goMy()
				// 屏蔽广告时候添加次数
				// this.setConnectNumber()
				// 暂时屏蔽广告
				this.showAd()
			},
			connect(maunal = false) {
				console.log('进入连接模式')
				// 判断接口数据是否加载
				if (this.wifi.length <= 0) {
					return uni.showToast({
						icon: 'none',
						title: '数据未加载，请重新点击连接'
					})
				}

				// 连接或者已经连上
				if (this.linking || this.is_linked) {
					return uni.showToast({
						icon: 'none',
						title: '正在连接或已连接成功'
					})
				}
				uni.showLoading({
					mask: true,
					title: '正在连接'
				})
				this.linking = true;
				let maunalRetry = false;
				// console.log('connectwifi', maunalRetry)
				this.linked_acount = this.wifi.id
				uni.connectWifi({
					SSID: this.wifi.account,
					password: this.wifi.pass,
					maunal: maunal,
					success: (res) => {
						// console.log('链接wifi结果', res, maunalRetry);
						this.checkLink(maunal, maunalRetry);
					},
					fail: (err) => {
						// 初始化数据
						this.linking = false
						this.is_linked = false
						this.checkLink(maunal, maunalRetry);
						console.log(err, err.errMsg, errCodeMap['' + err.errCode])
						uni.showToast({
							icon: "none",
							title: errCodeMap['' + err.errCode] || '连接失败',
						})
					},
					complete: () => {
						// console.log('链接wificomplete结果', maunalRetry);
					}
				})
			},
			// 检测是否连接
			checkLink(maunal, maunalRetry) {
				uni.startWifi({
					success: () => {
						uni.getConnectedWifi({
							success: ({
								wifi
							}) => {
								// console.log('是否已链接', wifi.SSID, this.wifi.account);
								this.is_linked = (wifi.SSID === this.wifi.account)
								let success = this.is_linked
								let systemInfo = this.getSysOs()
								maunalRetry = !maunal && systemInfo.isAndroid10laest
								// console.log('complete', maunal, systemInfo.isAndroid10laest, success, maunalRetry)
								// 不管什么版本，直接连接成功
								this.connectSuccess(success, maunalRetry)
								// console.log('android 10以上手机第一次自动连接失败时需要手动连接')
								//android 10以上手机第一次自动连接失败时需要手动连接
								this.handelSAndroid10(success, maunalRetry, maunal)

								// console.log('没有连接成功，也不是版本问题')
								this.connectFail(success, maunalRetry)
								// 没有连接成功，也不是版本问题
							},
							fail: (err) => {
								// console.log(err)
								this.linking = false
								this.is_linked = false
								return uni.showToast({
									icon: 'none',
									title: '密码错误',
									duration: 5000
								})
							},
						})
					},
					fail: (err) => {
						// console.log('打开wifi失败', err)
						return uni.showToast({
							icon: 'none',
							title: '打开wifi失败'
						})
					}
				})
				// console.log('return', this.is_linked)
			},
			getSysOs() {
				let systemInfo = uni.getSystemInfoSync();
				systemInfo.navbarHeight = systemInfo.platform == 'ios' ? 44 : 48;
				systemInfo.isIOS = systemInfo.system?.toLowerCase().indexOf('ios') > -1;
				systemInfo.isAndroid = systemInfo.system?.toLowerCase().indexOf('android') > -1;
				if (systemInfo.isAndroid) {
					try {
						systemInfo.isAndroid10laest = Number(systemInfo.osVersion) >= 10
					} catch (err) {
						systemInfo.isAndroid10laest = true;
					}
				}
				// console.log('系统信息',systemInfo)
				return systemInfo
			},
			setConnent(item) {
				this.wifi = item
				// 初始化数据
				this.linking = false
				this.is_linked = false
				this.goMy()
				// 判断登录情况和连接数
				if (this.connect_number <= 0) {
					return uni.showModal({
						title: '连接数不足',
						content: '观看广告能获取连接数',
						cancelText: '取消',
						confirmText: '确定',
						success: (res) => {
							if (res.confirm) {
								// 显示设置
								this.add()

							} else {

							}
						}
					});
				}
				// 消耗连接数
				this.setConnectNumberDec()

				uni.startWifi({
					success: () => {
						// console.log('打开wifi成功')
						uni.getConnectedWifi({
							success: ({
								wifi
							}) => {
								// console.log('点击按钮')
								this.is_linked = (wifi.SSID === this.wifi.account)
								if (this.is_linked) {
									this.linked_acount = this.wifi.id
									this.setWifiFirst()
									return uni.showToast({
										icon: 'none',
										title: '连接成功'
									})
								} else {
									this.connect(); //第一次自动连接
								}
							},
							fail: (err) => {
								this.connect(); //第一次自动连接
							}
						})
					},
					fail: (err) => {
						// console.log('打开wifi失败', err)
						return uni.showToast({
							icon: 'none',
							title: '打开wifi失败'
						})
					}
				});
			},
			// 连接成功
			connectSuccess(success, maunalRetry) {
				if (success) {
					this.linking = false;
					uni.hideLoading();
					this.linked_acount = this.wifi.id
					this.setWifiFirst()
					return uni.showToast({
						icon: 'none',
						title: '连接成功'
					})
				}
				if (success || !maunalRetry) {
					// console.log('complete3', success, maunalRetry)
					this.linking = false;
					uni.hideLoading();
					if (success) {
						this.linked_acount = this.wifi.id
						this.setWifiFirst()
						return uni.showToast({
							icon: 'none',
							title: '连接成功'
						})
					} else {
						return uni.showToast({
							icon: 'none',
							title: '密码错误',
							duration: 5000
						})
					}
				}
			},
			// android 10版本
			handelSAndroid10(success, maunalRetry, maunal) {
				var that = this
				// 没有成功，没有跳转并且安卓10，没有跳转
				if (!success && maunalRetry && !maunal) {
					that.linking = false;
					uni.hideLoading();
					return uni.showModal({
						title: '连接WIFI',
						confirmText: '跳转',
						content: `密码已复制,请手动选中【${that.wifi.account}】粘贴密码连接`,
						success: ({
							confirm
						}) => {
							if (confirm) {
								uni.setClipboardData({
									data: that.wifi.pass,
									success() {
										uni.startWifi({
											success: () => {
												// console.log('打开wifi成功')
												that.connect(true)
											},
											fail: (err) => {
												// console.log('打开wifi失败', err)
											}
										});
									}
								})
							}
						}
					})
				}
			},
			connectFail(success, maunalRetry) {
				var that = this
				if (!success && !maunalRetry) {
					that.linking = false;
					uni.hideLoading();
					return uni.showModal({
						title: '连接WIFI',
						confirmText: '跳转',
						content: `密码已复制,请手动选中【${that.wifi.account}】粘贴密码连接`,
						success: ({
							confirm
						}) => {
							if (confirm) {
								uni.setClipboardData({
									data: that.wifi.pass,
									success() {
										uni.startWifi({
											success: () => {
												// console.log('打开wifi成功')
												that.connect(true)
											},
											fail: (err) => {
												// console.log('打开wifi失败', err)
											}
										});
									}
								})
							}
						}
					})
				}
			},
			setWifiFirst() {
				let listData = this.list
				for (var i = 0; i < listData.length; i++) {
					if (listData[i].id == this.wifi.id) {
						listData.splice(i, 1) //先把符合条件的数据从当前数组中删除
						break;
					}
				}
				listData.unshift(this.wifi) //通过unshift函数把符合要求的数据放到第一位
			},
			getWifiList() {
				var that = this
				if (this.wifiList.length > 0) {
					return false
				}
				// 如果是ios，需要手动打开设置
				let systemInfo = this.getSysOs()
				console.log(systemInfo.isIOS)
				if (systemInfo.isIOS) {
					console.log('当前系统');
					// ios版本，直接查询
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							console.log('当前位置的经度：' + res.longitude);
							console.log('当前位置的纬度：' + res.latitude);
							that.getList(res.longitude, res.latitude)
						}
					});


				} else {
					this.openGetWifiList()
				}
				uni.onGetWifiList((res) => {
					// console.log(res)
					this.wifiList = []
					let list = res.wifiList
					list.forEach((item, index, list) => {
						console.log('item =>', item)
						this.wifiList.push(item.SSID)
						this.show_tips = false
					})
					this.getList()
				})
			},
			openGetWifiList() {
				var that = this
				uni.startWifi()
				uni.getWifiList({
					success: () => {},
					fail(err) {
						console.log(err)
						if (err.errno == '1505002') {
							uni.showToast({
								icon: 'none',
								title: '需要手动打开wifi',
								duration: 5000
							})
						}
						// gps无法开启
						if (err.errno == '1505004') {
							uni.getLocation({
								type: 'gcj02',
								success: function(res) {
									// console.log('当前位置的经度：' + res.longitude);
									// console.log('当前位置的纬度：' + res.latitude);
									that.getList(res.longitude, res.latitude)
								}
							});
						}
					}
				})
			},
			setConnectNumber() {
				this.$http.post('connectionsUp', {}).then(res => {
					this.connect_number += 1
					return uni.showToast({
						icon: 'none',
						title: res.data.msg
					})
				}).catch(err => {

				})
			},
			getUser() {
				this.$http.get('user', {}).then(res => {
					uni.setStorageSync('user', res.data.data)
				}).catch(err => {

				})
			},
			setConnectNumberDec() {
				this.$http.post('connectionsDec', {}).then(res => {
					this.connect_number -= 1
				}).catch(err => {

				})
			},
			goMy() {
				let token = uni.getStorageSync('token')
				if (!token) {
					uni.showModal({
						title: '还没有登录呢',
						confirmText: '确定',
						showCancel: false,
						success: (res) => {
							return uni.switchTab({
								url: '/pages/my/my'
							})
						}
					});

				}
			}
		},
	};
</script>

<style scoped lang="scss">
	.page {
		background-color: #f9f9f9;
		width: 100%;
		overflow-y: auto;
		overflow-x: hidden;
		height: 100%;

		.ios {
			position: fixed;
			z-index: 2;
			width: 100%;
			height: 100%;
			background: #6e6a6a;
			text-align: center;

			.close {
				top: 323rpx;
				right: 80rpx;
				position: fixed;

				image {
					width: 50rpx;
					height: 50rpx;
				}
			}

			.tip_img {
				width: 80%;
				height: 60%;
				margin-top: 40%;
			}
		}

		.btn {
			margin-top: 50rpx;
			border: solid 1px #22b14C21;
			background-color: #82c6f417;
			color: #97a1b7;
		}

		.vimg {
			height: 300rpx;
			width: 100%;
			position: absolute;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.section {
			padding: 100rpx 0 100rpx;
			background-color: #ffffff;
			border-radius: 20rpx;
			margin: 0rpx 20rpx 0 20rpx;

			.text {
				color: #000000;
				font-size: 36rpx;
				font-family: SourceHanSansCN;
				line-height: 34rpx;
			}

			.space-y-22 {

				&>view:not(:first-child),
				&>text:not(:first-child),
				&>image:not(:first-child) {
					margin-top: 44rpx;
				}

				.text_2 {
					color: #000000;
					font-size: 48rpx;
					font-family: SourceHanSansCN;
					line-height: 36rpx;
				}

				.button {
					padding: 24rpx 0;
					background-color: #22b14C;
					border-radius: 20rpx;
					width: 194rpx;

					.text_3 {
						color: #ffffff;
					}
				}
			}
		}

		.space-y-26 {

			&>view:not(:first-child),
			&>text:not(:first-child),
			&>image:not(:first-child) {
				margin-top: 52rpx;
			}

			z-index: 1;
			margin-top: 200rpx !important;
		}

		.section_2 {
			padding: 24rpx 26rpx 284rpx 52rpx;
			background-color: #ffffff;
			border-radius: 20rpx;
			margin: 0rpx 20rpx 0 20rpx;

			.text_4 {
				color: #000000;
			}

			.list {
				padding-left: 8rpx;

				.space-x-10 {

					&>view:not(:first-child),
					&>text:not(:first-child),
					&>image:not(:first-child) {
						margin-left: 20rpx;
					}

					.image {
						margin-bottom: 4rpx;
						width: 60rpx;
						height: 60rpx;
					}

					.space-y-8 {

						&>view:not(:first-child),
						&>text:not(:first-child),
						&>image:not(:first-child) {
							margin-top: 16rpx;
						}

						.font_2 {
							font-size: 28rpx;
							font-family: SourceHanSansCN;
							line-height: 21rpx;
							color: #000000;
						}
					}
				}

				.text-wrapper {
					padding: 16rpx 0;
					background-color: #22b14C4f;
					border-radius: 60rpx;
					width: 156rpx;
					height: 58rpx;

					.font_3 {
						font-size: 23rpx;
						font-family: SourceHanSansCN;
						line-height: 26rpx;
						color: #22b14C;
					}
				}

				.vcon {
					display: flex;
					flex-direction: row;
					align-items: center;

					.vcimg {
						width: 36rpx;
						height: 36rpx;
						margin-right: 10rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}

					.font_con {
						font-size: 23rpx;
						width: 3rem;
						height: 30rpx;
					}
				}
			}

			.space-y-38 {

				&>view:not(:first-child),
				&>text:not(:first-child),
				&>image:not(:first-child) {
					margin-top: 76rpx;
				}
			}
		}

		.space-y-36 {

			&>view:not(:first-child),
			&>text:not(:first-child),
			&>image:not(:first-child) {
				margin-top: 72rpx;
			}
		}

		.font_1 {
			font-size: 28rpx;
			font-family: SourceHanSansCN;
			line-height: 26rpx;
			color: #a6a6a6;
		}
	}

	.space-y-27 {

		&>view:not(:first-child),
		&>text:not(:first-child),
		&>image:not(:first-child) {
			margin-top: 20rpx;
		}
	}
</style>